import configs
from configs import languages
from utils import service_functions
from speech_parsing import *
from template.singleton import Singleton
from .class_set_calls import Class_set_calls


class Calls_funcs(Class_set_calls, Singleton):
    def shell_scheduler(self, id_func, func_name, call_shell, tags=[]):
        # Оболочка вызова
        # Например в цикле
        search = service_functions.del_func_str(
            func_name, configs.speech_recognition_str_api
        )
        if call_shell == "searhc":
            # print("\n\n\n\n\n\n\n\n\n",configs.speech_recognition_str_api)
            self.import_config_into_func(id_func, func_name, search)

        elif call_shell == "local_net_cmd":
            self.import_config_into_func(id_func, func_name, search)
        else:
            pass

    def call_function(self, func: str, tags: list = []):
        if self.consent_for_activation(func):
            if configs.cmds_void[func]["function_classification"] == "egg":
                self.function_call_processing(func, self.obj_import_egg, tags)
            elif configs.cmds_void[func]["function_classification"] == "core_utilities":
                if configs.cmds_void[func]["class_name"] == "Apps":
                    self.obj_import_core_app.class_name(self.obj_apps)
                elif configs.cmds_void[func]["class_name"] == "Settings_Kernel":
                    self.obj_import_core_app.class_name(self.obj_settings)
                self.function_call_processing(func, self.obj_import_core_app, tags)
            elif configs.cmds_void[func]["function_classification"] == "collection":
                self.wrapper_collection_functions(func)

    def import_config_into_func(self, id_func, func, tags=[]):
        # try:
        if configs.cmds["void"][func]["config_void_func"] == "no_import":
            if tags:
                # print(tags," dnfklhzdlknkjn;jd fdfh")
                mess = id_func(tags)
                self.obj_control_mess.message_typle(mess)
            else:
                mess = id_func()
                self.obj_control_mess.message_typle(mess)
        elif configs.cmds["void"][func]["config_void_func"] == "import":
            if tags:
                # print({func:configs.cmds["void"][func]})
                mess = id_func(tags, {func: configs.cmds["void"][func]})
                self.obj_control_mess.message_typle(mess)
            else:
                mess = id_func(func, {func: configs.cmds["void"][func]})
                self.obj_control_mess.message_typle(mess)
        # except:
        # self.obj_control_mess.message("Ошибка вызова функции")

    def function_call_processing(self, func: str, class_import_obj, tags: list = []):
        # tags:list=[] ?
        class_import_obj.keys(func)
        id_func = class_import_obj.import_func()
        if configs.cmds_void[func]["call shell"] == "standard":
            if "const" in configs.cmds_void[func]["tags"]:
                tags = configs.cmds_void[func]["tags"]["const"]["tags_list"]
                self.import_config_into_func(id_func, func, tags)
            elif "None" in configs.cmds_void[func]["tags"]:
                self.import_config_into_func(id_func, func)
            else:
                # print("жопа 22222")
                self.import_config_into_func(id_func, func, tags)
        elif configs.cmds_void[func]["call shell"] != "standard":
            self.shell_scheduler(id_func, func, configs.cmds_void[func]["call shell"])

    def label_approval(self, func: str) -> bool:
        """Проверка вызываемой команды является вызванная функция с параметрами

        Если True, то функция не имеет параметров.
        Если False, то имеет параметры.

        """
        return ("None" in configs.cmds_void[func]["tags"]) or (
            "const" in configs.cmds_void[func]["tags"]
        )

    def consent_for_activation(self, ch_func):
        """
        Данная функция спращивает разрещение на активацию вызываемой функции.

        Параметры:
        `ch_func`: Имя функции

        **enabling_activation** глобальный параметр разрещения на запрос об активации.
        Также в каждой функции есть локальный парметр разрещения на активацию
        Исправить: Локальный парметр в случае запрета не спрашвиает разрешение на активацию

        Возращает:
        **Булевый тип**
        True в случае разращения на активацию
        False в случае запрета на активацию

        """
        if configs.enabling_activation:
            if configs.cmds_void[ch_func]["speech test"]:
                yes = configs.cmds["other"]["yes"]
                no = configs.cmds["other"]["no"]
                self.obj_control_mess.message(
                    languages["call_funcs=>Calls_funcs"][
                        "util_consent_for_activation_CALL_FUNC"
                    ]
                )
                consent = service_functions.queue_voice_time_str_api()
                if consent in yes:
                    self.obj_control_mess.message(
                        languages["call_funcs=>Calls_funcs"][
                            "util_consent_for_activation_CMD_TRUE"
                        ]
                    )
                    return True
                elif consent in no:
                    self.obj_control_mess.message(
                        languages["call_funcs=>Calls_funcs"][
                            "util_consent_for_activation_CMD_FALSE"
                        ]
                    )
                    return False
                else:
                    self.obj_control_mess.message(
                        languages["call_funcs=>Calls_funcs"][
                            "util_consent_for_activation_CMD_REC"
                        ]
                    )
                    return False
        else:
            return True

    def wrapper_collection_functions(self, name_collection):
        # Оболочка коллекций collection_functions
        if not configs.hidden_function:
            if name_collection in configs.cmds["collection"]:
                funcs = configs.cmds["collection"][name_collection]
                # Может быть рекурсия, ОПАСНО !!!
                self.collection_functions(funcs)
            else:
                self.obj_control_mess.message(
                    languages["call_funcs=>Calls_funcs"][
                        "wrapper_collection_functions_COLLECT"
                    ]
                )
        elif configs.hidden_function:
            if name_collection in configs.cmds["collection"]:
                funcs = configs.cmds["collection"][name_collection]
                self.obj_control_mess.mute_out()
                self.collection_hidden_function_execution_no_m(funcs)
                self.obj_control_mess.mute_out()

    def collection_functions(self, funcs):
        for func in funcs:
            if "tags" in configs.cmds_void[func]["tags"]:
                temp = languages["call_funcs=>Calls_funcs"][
                    "collection_functions_SPEECH_TAGS_FUNC"
                ]
                self.obj_control_mess.message(temp)
                if configs.tags_decoder_flag:
                    tags = self.obj_tags_wrap.selection_tags()
                    self.call_function(func, tags)
                elif not configs.tags_decoder_flag:
                    tags = self.obj_tags_wrap.selection_tags(
                        service_functions.queue_voice_time_str_api()
                    )
                    self.call_function(func, tags)
            elif "const" in configs.cmds_void[func]["tags"]:
                tags = configs.cmds_void[func]["tags"]["const"]["tags_list"]
                self.call_function(func, tags)
            elif "None" in configs.cmds_void[func]["tags"]:
                self.call_function(func)
            elif "key" in configs.cmds_void[func]["tags"]:
                # !!!
                # tags = configs.cmds_void[func]["tags"]["key"]["tags_list"]
                self.call_function(func, tags)

    def collection_hidden_function_execution_no_m(self, funcs):
        for func in funcs:
            if "const" in configs.cmds_void[func]["tags"]:
                tags = configs.cmds_void[func]["tags"]["const"]["tags_list"]
                self.call_function(func, tags)
            elif "None" in configs.cmds_void[func]["tags"]:
                self.call_function(func)
        self.obj_control_mess.message(
            languages["call_funcs=>Calls_funcs"][
                "collection_hidden_function_execution_no_m"
            ]
        )

    def activation_mess(self, dict_mess):
        cmd_str = service_functions.queue_voice_time_str_api()
        value = self.obj_wrap_decoder.search_key_cmd(cmd_str, "other")
        if "yes" in value:
            self.obj_control_mess.message(dict_mess["yes"])
            return True
        if "no" in value:
            self.obj_control_mess.message(dict_mess["no"])
            return False
        else:
            self.obj_control_mess.message(dict_mess["else"])
            return False
